<?php

namespace App\Console\Commands;

use App\Libs\Util;
use App\Libs\WeChat\Transfer\WxTransfer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SendText extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:sendtext';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'sendtext';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            echo memory_get_usage();
            //SELECT activity_team.at_id,COUNT(*) FROM `activity_team` LEFT JOIN activity_users ON activity_users.at_id = activity_team.at_id WHERE activity_team.at_id = 39 GROUP BY activity_users.at_id
            $activity = DB::table('activity')->where(['is_valid'=>1])->get();
            var_dump($activity);
            if($activity){
                foreach ($activity as $values){
                    //如果过期了 直接没成功的退款
                    if(strtotime($values->end_time) <= time() ){
                        $activity_goods = DB::table('activity_goods')->leftjoin('activity_team','activity_goods.sku','=','activity_team.sku')->where(['activity_id'=>$values->ac_id])->get(['goods_id','activity_goods.sku']);
                        //var_dump($activity_goods);exit;
                        foreach ($activity_goods as $v){
                            //查询队伍
                            $activity_team = DB::table('activity_team')->where(['activity_goods_id'=>$v->goods_id,'sku'=>$v->sku,'ac_id'=>$values->ac_id])->get();
                            foreach ($activity_team as $value){
                                //查询队伍人数是否足够 不够的话 查询订单退款
                                $activity_users = DB::table('activity_users')->where(['at_id'=>$value->at_id,'activity_goods_id'=>$v->goods_id,'sku'=>$v->sku])->get();
                                $nums = count($activity_users);
                                if($values->team_num){
                                    $judge_num = $values->activity_num;
                                }else{
                                    $judge_num = $values->activity_num-1;
                                }
                                if($nums >= ($judge_num)){
                                    continue;
                                }else{
                                    //查询订单信息并退款
                                    foreach ($activity_users as $item){
                                        $str = $item->user_id.'_'.$v->goods_id.'_'.$v->sku.'_'.$value->at_id.'_'.$values->ac_id;
                                        $orders = DB::table('ibrand_order')->where(['user_id'=>$item->user_id,'channel'=>$str])->first();
                                        //var_dump($orders);
                                        if($orders){
                                            //如果状态不对 记录
                                            if($orders->status!=2){
                                                savelog('refund_pintuan', (json_encode($orders)));
                                                continue;
                                            }
                                            $wx = new WxTransfer();
                                            $refund = [];
                                            $refund['order_no']=$orders->order_no;
                                            $refund['total_fee']=$orders->total;
                                            $res = $wx->refund($refund);
                                            if($res){
                                                //修改订单的状态
                                                DB::table('ibrand_order')->where(['order_no'=>$orders->order_no])->update(['status'=>7]);
                                                $user = DB::table('ibrand_user')->where(['id'=>$orders->user_id])->first();
                                                $openid = $user->openid;
                                                //退还积分
                                                $member_info = get_member($openid);
                                                if($member_info){
                                                    $before_bonus = $member_info->bonus;
                                                    $change_bonus = ceil($orders->total/100);
                                                    $after_bonus = $before_bonus-$change_bonus;
                                                    $status = 1;
                                                    $type = 2;
                                                    //调用微信的接口加积分
                                                    $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                                    $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                                    if($result['errcode']==0){
                                                        add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                                    }else{
                                                        savelog('wx_bonus', '订单已经支付过'.$orders->order_no.'错误：'.$result['errmsg']);
                                                    }
                                                }

                                                echo '退款成功';
                                                savelog('refund_pintuan_success', (json_encode($orders)));
                                            }else{
                                                savelog('refund_pintuan_fail', (json_encode($orders)));
                                            }
                                        }else{
                                            savelog('refund_pintuan_fail', (json_encode($str)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else{
                        //判断队伍人数是否足够 如果足够判断每个队伍的人数 如果每个队伍人数都满的话 则算成功 否则不成功不做操作
                        //$activity_team = DB::table('activity_team')->where(['ac_id'=>$values->ac_id])->get();
                        if($values->team_num){
                            $res = DB::select("SELECT activity_users.ac_id,COUNT(*) AS ac_num FROM `activity_team` LEFT JOIN activity_users ON activity_users.at_id = activity_team.at_id WHERE activity_team.ac_id = ? GROUP BY activity_users.at_id HAVING ac_num >= ?",[$values->ac_id,$values->activity_num]);
                            $team_num = count($res);
                            //说明团数和人数都已经足够了
                            if($team_num >= $values->team_num){
                                //结束活动之后要把没有成团的队伍退款
                                $activity_team = DB::table('activity_team')->where(['ac_id'=>$values->ac_id])->get();
                                if(!$activity_team){
                                    continue;
                                }
                                foreach ($activity_team as $value){
                                    //查询队伍人数是否足够 不够的话 查询订单退款
                                    $activity_users = DB::table('activity_users')->where(['at_id'=>$value->at_id])->get();
                                    $nums = count($activity_users);
                                    //如果小于
                                    if($nums < ($values->activity_num)){
                                        //查询订单信息并退款
                                        foreach ($activity_users as $item){
                                            $str = $item->user_id.'_'.$item->activity_goods_id.'_'.$item->sku.'_'.$value->at_id.'_'.$values->ac_id;
                                            $orders = DB::table('ibrand_order')->where(['user_id'=>$item->user_id,'channel'=>$str])->first();
                                            //var_dump($orders);
                                            if($orders){
                                                //如果状态不对 记录
                                                if($orders->status!=2){
                                                    savelog('refund_pintuan', (json_encode($orders)));
                                                    continue;
                                                }
                                                $wx = new WxTransfer();
                                                $refund = [];
                                                $refund['order_no']=$orders->order_no;
                                                $refund['total_fee']=$orders->total;
                                                $res = $wx->refund($refund);
                                                if($res){
                                                    //修改订单的状态
                                                    DB::table('ibrand_order')->where(['order_no'=>$orders->order_no])->update(['status'=>7]);
                                                    $user = DB::table('ibrand_user')->where(['id'=>$orders->user_id])->first();
                                                    $openid = $user->openid;
                                                    //退还积分
                                                    $member_info = get_member($openid);
                                                    if($member_info){
                                                        $before_bonus = $member_info->bonus;
                                                        $change_bonus = ceil($orders->total/100);
                                                        $after_bonus = $before_bonus-$change_bonus;
                                                        $status = 1;
                                                        $type = 2;
                                                        //调用微信的接口加积分
                                                        $record_bonus = sprintf("退还%s元，扣除%u积分", $change_bonus, $change_bonus);
                                                        $result = Util::updateMember($member_info->code,$record_bonus,-$change_bonus);
                                                        if($result['errcode']==0){
                                                            add_bonus_record($openid,$before_bonus,$change_bonus,$after_bonus,$status,$type,1,'');
                                                        }else{
                                                            savelog('wx_bonus', '订单已经支付过'.$orders->order_number.'错误：'.$result->errmsg);
                                                        }
                                                    }

                                                    echo '退款成功';
                                                    savelog('refund_pintuan_success', (json_encode($orders)));
                                                }else{
                                                    savelog('refund_pintuan_fail', (json_encode($orders)));
                                                }
                                            }else{
                                                savelog('refund_pintuan_fail', (json_encode($str)));
                                            }
                                        }
                                    }

                                }
                                //说明团队已经足够了 可以结束了活动了
                                DB::table('activity')->where(['ac_id'=>$values->ac_id])->update(['is_valid'=>0]);
                                savelog('pintuan_succeed', (json_encode($values)));
                            }
                        }
                    }
                }
            }
            echo '<br/>';
            echo memory_get_usage();
            echo '暂无需要退款活动';

        } catch (\Exception $ex) {
            var_dump($ex->getMessage() . $ex->getLine());
            savelog('export_ald_log', $ex->getMessage() . $ex->getLine());
        }
    }
}


//foreach ($activity as $item){
//    //判断活动是否已经过期
//    if(strtotime($item->end_time) <= time() ){
//        $date_over = 1;
//    }else{
//        $date_over = 0;
//    }
//    //判断有没有成团数限制 1.如果没有则判断成团人数 如果人数够设置的成团数减一 则成团成功 2.如果有限制 则判断成团的人数 如果够了就直接结束
//    /*$activity_team = DB::table('activity_team')->where(['ac_id'=>$item->ac_id])->get();
//    if($item->team_num){
//        $team_num = count($activity_team);
//        if($team_num){
//
//        }
//    }else{
//
//    }*/
//    //判断
//    //如果活动时间结束了 判断是否拼团成功
//    $activity_goods = DB::table('activity_goods')->leftjoin('activity_team','activity_goods.sku','=','activity_team.sku')->where(['activity_id'=>$activity->ac_id])->get(['goods_id','activity_goods.sku']);
//    foreach ($activity_goods as $v){
//        //查询队伍
//        $activity_team = DB::table('activity_team')->where(['activity_goods_id'=>$v->goods_id,'sku'=>$v->sku])->get();
//
//    }
//}